<template>
  <el-form
    :model="ruleForm"
    :rules="rules"
    ref="ruleForm"
    label-width="100px"
    class="demo-ruleForm login-box"
  >
    <h3 class="login-title">欢迎!</h3>
    <el-form-item label="账户:" prop="username" label-width="55px">
      <el-input
        type="text"
        placeholder="请输入账户名"
        v-model="ruleForm.username"
      ></el-input>
    </el-form-item>
    <el-form-item label="密码:" prop="password" label-width="55px">
      <el-input
        type="password"
        placeholder="请输入密码"
        v-model="ruleForm.password"
      ></el-input>
    </el-form-item>

    <el-form-item label-width="0" class="login-login-button">
      <el-button type="primary" @click="submitForm('ruleForm')">登入</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { ElMessage } from "element-plus";

export default {
  name: 'Login',
  data() {
    return {
      ruleForm: {
        username: "",
        password: "",
      },
      rules: {
        username: [
          { required: true, message: "账号不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let that = this;
          this.$axios({
            method: "post",
            url: "/user/login",
            data: {
              username:this.$data.ruleForm.username,
              password:this.$data.ruleForm.password,
            },
          }).then(function (response) {
              // console.log(response);
              if(response.data.code == 1) {
                window.sessionStorage.setItem('user', JSON.stringify(response.data));
                ElMessage.success({
                  message: '登入成功!欢迎您!',
                  type: 'success'
                });
                that.$router.push('/main');
              }else {
                ElMessage.warning({
                  message: "账户名或密码错误",
                  type: "warning",
                });
                return false;
              }
          }).catch(function (error) {
              console.log(error);
              ElMessage.error(error.message)
          });
        } else {
          ElMessage.warning({
            message: "请输入账号或密码",
            type: "warning",
          });
          return false;
        }
      });
    },
  },
};
</script>

<style scoped>
.login-box {
  width: 350px;
  margin: 120px auto;
  border: 1px solid #dcdfe6;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 0 30px #dcdfe6;
  font-size: 20px;
}
.login-title {
  text-align: center;
}
.login-login-button {
  text-align: center;
}
</style>
